import Taro from '@tarojs/taro'
class MyVue {
  static EVENT_TYPE = {
    REACH_BOTTOM: 'onReachBottom', //滑动到底部
    PULL_DOWN_REFRESH: 'onPullDownRefresh', //滑动到底部
  }
  constructor(option) {
    this.init(option)
  }
  init(option) {
    // eslint-disable-next-line no-unused-vars
    for (const key in option) {
      if (Object.hasOwnProperty.call(option, key)) {
        this[key] = option[key]
      }
    }
  }

  //下拉刷新
  onPullDownRefresh = () => {
    const instance = Taro.getCurrentInstance().page
    const path = (instance.route || instance.path).split('?')[0]
    Taro.eventCenter.trigger(path + TzVue.EVENT_TYPE.PULL_DOWN_REFRESH)
  }
  //滑动底部加载更多
  onReachBottom = function () {
    const path = this.tid.split('?')[0]
    Taro.eventCenter.trigger(path + TzVue.EVENT_TYPE.REACH_BOTTOM)
  }

  //销毁
  unmounted = function () {
    const instance = Taro.getCurrentInstance().page
    const path = (instance.route || instance.path).split('?')[0]
    Taro.eventCenter.off(path + TzVue.EVENT_TYPE.REACH_BOTTOM)
    Taro.eventCenter.off(path + TzVue.EVENT_TYPE.PULL_DOWN_REFRESH)
  }
}

/**
 * 下拉刷新回调对外使用
 * @param {function} fn
 */
export const usePullDownRefresh = (fn) => {
  const instance = Taro.getCurrentInstance().page
  const path = (instance.route || instance.path).split('?')[0]
  Taro.eventCenter.on(path + TzVue.EVENT_TYPE.PULL_DOWN_REFRESH, fn)
}

/**
 * 回调对外使用
 * @param {function} fn
 */
export const useReachBottom = (fn) => {
  const instance = Taro.getCurrentInstance().page
  const path = (instance.route || instance.path).split('?')[0]
  Taro.eventCenter.on(path + TzVue.EVENT_TYPE.REACH_BOTTOM, fn)
}

export default TzVue
